package aip.assignment2.webservice;

import aip.assignment2.persistence.entity.Purchase;
import aip.assignment2.service.PurchaseManager;
import aip.assignment2.webservice.exception.UpdatePurchaseException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.jws.WebMethod;
import javax.jws.WebService;

/**
 * This class contains web service for supplier access
 */
@WebService
public class Supplier
{
	@EJB
	private PurchaseManager m_PurchaseManager;
	/**
	 * This method lists all unpaid purchases.
	 */
	@WebMethod
	public List<aip.assignment2.webservice.entity.Purchase> list()
	{
		//TODO write your implementation code here:
		List<Purchase> purchases = m_PurchaseManager.getPaidPurchases();
		List<aip.assignment2.webservice.entity.Purchase> results = new ArrayList<aip.assignment2.webservice.entity.Purchase>();
		for (Purchase purchase : purchases)
		{
			results.add(aip.assignment2.webservice.entity.Purchase.createFromJpaEntity(purchase));
		}
		return results;
	}
	/**
	 * This method updates an existing purchase's status.
	 */
	@WebMethod
	public void update(String number, String status) throws UpdatePurchaseException
	{
		if (number == null || !status.equals("SENT"))
		{
			throw new UpdatePurchaseException();
		}
		Purchase purchase = m_PurchaseManager.getPurchaseByNumber(number);
		if (purchase == null || !purchase.getStatus().equals("PAID"))
		{
			throw new UpdatePurchaseException();
		}
		purchase.setStatus(status);
		m_PurchaseManager.update(purchase);
	}
}
